
class ApiController {
    static instance;
    static getInstance() {
        if (false === this.instance instanceof this) {
            this.instance = new this;
        }
        return this.instance;
    }


    constructor() {
        this._middles = [];
    }

    use(middle) {
        const list = this._middles;
        const flag = this._middles.filter((item, index) => {
            return item.controllerName === middle.controllerName;
        });
        if (flag.length === 0) {
            this._middles.push(middle);
        }

    }

    run(req, callback) {
        //console.log(req.method);
        //console.log(req.url);
        //const str = 'api/article/addarticle?xxx=bb&cc=aaa';

        const url = req.url.split('?');
        const router = url[0].split('/');
        const errorResult = false;
        if (router.length > 1) {
            //API数组示例['','api','mmodule','Todo']，长度是4
            if (router[1].toLowerCase() === 'api' && router.length === 4) {
                const moduleName = router[2].toLowerCase();
                const TodoName = router[3].toLowerCase();
                //找到对应模块
                const _controllers = this._middles.filter((item, index) => {
                    return item.controllerName.toLowerCase() === moduleName;
                });
                if (_controllers.length === 1) {
                    const _controller = _controllers[0];
                    ///找到对应操作
                    const _todos = _controller.todoList.filter((item, index) => {
                        return item.name.toLowerCase() === TodoName;
                    });
                    if (_todos.length === 1) {
                        const todo = _todos[0];
                        //执行操作
                        todo.todo(req, callback);
                    }
                    else {
                        if (callback) {
                            callback(errorResult)
                        }
                    }
                }
                else {
                    if (callback) {
                        callback(errorResult)
                    }
                }
            }
            else {
                if (callback) {
                    callback(errorResult)
                }
            }

        }
        else {
            if (callback) {
                callback(errorResult)
            }
        }
    }

    //  router.forEach((item, index) => {
    //     console.log(item);
    //      console.log(index);
    //     if (item !== '') {

    //     }
    // });
    //  const _controller = this._middles.filter((item, index) => {
    //     return item.controllerName === middle.controllerName;
    // });
    // console.log(_controller);


}

export default ApiController;